package networklogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddNetWorkLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddNetWorkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddNetWorkLogic {
	return &AddNetWorkLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddNetWorkLogic) AddNetWork(in *iotpb.AddNetWorkReq) (*iotpb.AddNetWorkResp, error) {
	network := in.GetParams()
	if network == nil || network.GetDeptId() == 0 || network.GetName() == "" || network.GetConfiguration() == "" ||
		network.GetType() == "" || network.GetCreateUser() == "" || network.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增网络组件失败：参数缺失"),
			tool.GetErrMsgFormat("insert network"), "params is not existed", in)
	}

	var data model.IotNetwork
	_ = copier.Copy(&data, in.GetParams())

	// 保存数据
	_, err := l.svcCtx.IotNetworkModel.InsertEx(l.ctx, nil, []*model.IotNetwork{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("insert network"), err, in)
	}

	return &iotpb.AddNetWorkResp{}, nil
}
